package school.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import school.domain.OrderDoctor;
import school.domain.OrderVol;
import school.domain.User;
import school.extra.base.BaseController;
import school.extra.context.Constant;
import school.mapper.OrderDoctorMapper;
import school.mapper.OrderVolMapper;
import school.service.UserService;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private OrderDoctorMapper orderDoctorMapper;
    @Autowired
    private OrderVolMapper orderVolMapper;


    @GetMapping("login")
    public String login() {
        return "login";
    }


    /**
     * 首页
     *
     * @param model
     * @return
     */
    @RequestMapping({"/", "index"})
    public String index(Model model) {

        model.addAttribute("tipMsg", session.getAttribute("tipMsg"));
        session.removeAttribute("tipMsg");
        if (sessionUser().getType().equals("admin")) {
            return "index-admin";
        }
        return "index";
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("login")
    public String login(String username, String password) {
        User user = userService.login(username, password);
        if (null == user) return forward("login", "用户名或密码错误");
        logger.info("【 登 录 】 用户:{}  ", user.getUsername());
        session.setAttribute(Constant.SESSION.ADMIN, user);
        return redirect("index");
    }


    @RequestMapping("logout")
    public String logout() {
        session.removeAttribute(Constant.SESSION.ADMIN);
        return redirect("index");
    }

    @GetMapping("orderVol")
    public String orderVol() {
        return "order-vol";
    }

    @GetMapping("orderDoctor")
    public String orderDoctor() {
        return "order-doctor";
    }

    @ResponseBody
    @PostMapping("orderDoctor")
    public String orderDoctor(OrderDoctor orderDoctor) {
        orderDoctor.setUserid(sessionUser().getId());
        orderDoctor.setUsername(sessionUser().getUsername());
        orderDoctorMapper.insertSelective(orderDoctor);
        return "预约成功";
    }

    @PostMapping("orderVol")
    public String orderVol(OrderVol orderVol,Model model) {
        orderVol.setUserid(sessionUser().getId());
        orderVol.setUsername(sessionUser().getUsername());
        orderVolMapper.insertSelective(orderVol);
        model.addAttribute("tipMsg","预约成功");
        return "order-doctor";
    }


}
